﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using WebCommit.Common.Helpers;
using WebCommit.Common.Entitys;
using WebCommit.Common.Models;
using NHibernate.Criterion;

namespace WebCommit.BizL.Commit
{
	public class CommitBiz
	{
		#region singleton
		public static CommitBiz CurrentInstance
		{
			get {
				if (_Instance == null)
					_Instance = new CommitBiz();
				return _Instance;
			}
		}

		private static CommitBiz _Instance = null;

		private CommitBiz()
		{ }
		#endregion

		private ISession GetSession()
		{
			ISession session = NHibernateHelper.GetSession(WebCommit.Common.Constants.Config.HBSessionKey_WebCommit);
			return session;
		}


		public TitleResponse ResolveTitle(Common.Models.TitleRequest request)
		{
			//直接通过id访问
			if (!String.IsNullOrEmpty(request.Id))
			{
				TitleResponse response = new TitleResponse() { WebTitle = GetWebTitleEntity(request.Id) };
				response.IsCanCommit = false;
				return response;
			}


			if (String.IsNullOrEmpty(request.Url))
			{
				return new TitleResponse() { WebTitle = null, IsCanCommit = false };
			}
			
			ISession sess = GetSession();
			//到已有评论中查找
			CommitEntity comm = sess.CreateCriteria<CommitEntity>()
				.Add(Expression.Eq("OriginalUrl", request.Url))
				.UniqueResult<CommitEntity>();
			WebTitleEntity wt;
			if (comm != null)
			{
				wt = sess.Get<WebTitleEntity>(comm.WebTitleID);
				return new TitleResponse() { WebTitle = wt, IsCanCommit = true };
			}
			//到webtitle中查找
			request = ResolveTitleRequest(request);
			if (request.Title != null)
			{
				wt = sess.CreateCriteria<WebTitleEntity>()
					.Add(Expression.Eq("Title", request.Title))
					.UniqueResult<WebTitleEntity>();
				if (wt != null)
					return new TitleResponse() { WebTitle = wt, IsCanCommit = true }; ;
			}
			else
			{
				return new TitleResponse() { WebTitle = null, IsCanCommit = false }; ;
			}
			//还没有评论过
			if (string.IsNullOrEmpty(request.UserId))
				return new TitleResponse() { WebTitle = null, IsCanCommit = true }; ;
			wt = CreateWebTitleEntity(request);
			return new TitleResponse() { WebTitle = wt, IsCanCommit = true }; ;

		}

		private WebTitleEntity CreateWebTitleEntity(TitleRequest request)
		{
			ISession sess = GetSession();
			WebTitleEntity wt = new WebTitleEntity()
			{
				CreaterID = request.UserId,
				Title = request.Title
			};
			ITransaction tran = sess.Transaction;
			tran.Begin();
			sess.Save(wt);
			tran.Commit();
			return wt;

		}

		private TitleRequest ResolveTitleRequest(TitleRequest request)
		{
			//todo：核心解析算法，处理Title
			//todo：
			return request;
		}

		public Common.Entitys.WebTitleEntity GetWebTitleEntity(string id)
		{
			ISession sess = GetSession();
			return sess.Get<WebTitleEntity>(id);
		}
	}
}
